package com.store.practice.component;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.store.practice.dto.WebLog;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
@Order(1)
public class WebLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
    @Pointcut("execution(public * com.store.practice.controller.*.*(..))")
    public void webLog(){}

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint)throws Throwable{
    }

    @AfterReturning(value = "webLog()",returning = "ret")
    public void doAfterReturning(Object ret)throws Throwable{
    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        Long startTime = System.currentTimeMillis();
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object result = joinPoint.proceed();
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        WebLog webLog = new WebLog();
        if (method.isAnnotationPresent(ApiOperation.class)){
            ApiOperation annotation = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(annotation.value());
        }
        long endTime = System.currentTimeMillis();
        webLog.setMethod(method.getName());
        String strUrl = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(strUrl,URLUtil.url(strUrl).getPath()));
        webLog.setUrl(request.getRequestURL().toString());
        webLog.setUri(request.getRequestURI());
        webLog.setIp(request.getRemoteUser());
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime-startTime));
        webLog.setParameter(getParameter(method,joinPoint.getArgs()));
        logger.info("{}", JSONUtil.parse(webLog).toString());
        return result;
    }

    private Object getParameter(Method method,Object[] args){
        ArrayList<Object> argList = new ArrayList<>();
        Parameter[] parameters = method.getParameters();
        logger.info("parameters: {},args: {}",parameters,args);
        for (int i = 0; i < parameters.length; i++) {
            RequestBody requestBody = parameters[i].getAnnotation(RequestBody.class);
            RequestParam requestParam = parameters[i].getAnnotation(RequestParam.class);
            if (requestBody!=null){
                argList.add(args[i]);
            }
            if (requestParam!=null){
                Map<String, Object> map = new HashMap<>();
                String key = parameters[i].getName();
                if (StrUtil.isNotEmpty(requestParam.value())){
                    key = requestParam.value();
                }
                map.put(key,args[i]);
            }
            if (requestBody==null&&requestParam==null){
                argList.add(args[i]);
            }
        }
        if (argList.size()==0){
            return null;
        }else if (argList.size()==1){
            return argList.get(0);
        }else {
            return argList;
        }
    }
}
